package com.emm.yixun.estate.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.jws.WebService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.basic.enums.ModelEnum;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.MerchantService;
import com.emm.yixun.basic.service.ModelKeyService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.PriceSchemeService;
import com.emm.yixun.basic.service.ProjectHouseTypeService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.RoomChangeHistoryService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.common.app.QueryCustomerRoomListReqDto;
import com.emm.yixun.common.app.QueryCustomerRoomListResDto;
import com.emm.yixun.common.app.QueryProjectRoomInfoListReqDto;
import com.emm.yixun.common.app.QueryProjectRoomInfoListResDto;
import com.emm.yixun.common.app.servletentity.CustomerRoomListRes;
import com.emm.yixun.common.app.servletentity.ProjectRoomInfoListRes;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Merchant;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.PriceScheme;
import com.emm.yixun.common.model.PriceSchemeDetail;
import com.emm.yixun.common.model.ProjectHouseType;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.RoomChangeHistory;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.dto.MerchantDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.ProjectRoomPriceDto;
import com.emm.yixun.common.model.dto.RoomChangeHistoryDto;
import com.emm.yixun.common.model.dto.RoomPriceSchemeDetailDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.BusinessStatusEnum;
import com.emm.yixun.common.model.enums.DealCategoryEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.ProjectTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.model.pmo.GraphicalVo;
import com.emm.yixun.common.model.pmo.PicHighchartsVo;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.MathUtil;
import com.emm.yixun.config.DsfConfig;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;

@Service("projectRoomServiceFacade")
@WebService(name = "com.emm.yixun.estate.service.ProjectRoomServiceFacade")
public class ProjectRoomServiceFacadeImpl implements ProjectRoomServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private ProjectRoomService service;

	@Resource
	private ModelKeyService modelKeyService;

	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;

	@Autowired
	private PriceSchemeService priceSchemeService;
	
	@Autowired
	private PayDepositService payDepositService;
	
	@Autowired
	private SubscribeService subscribeService;
	
	@Autowired
	private DataPermissionService dataPermissionService;
	
	@Autowired
	private ProjectHouseTypeService projectHouseTypeService;
	
	@Autowired
	private MerchantService merchantService;
	
	@Autowired
	private RoomChangeHistoryService roomChangeHistoryService;
	

	@Override
	public Response<ProjectRoomDto> save(ProjectRoomDto dto) {
		Response<ProjectRoomDto> response = new Response<ProjectRoomDto>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
				return response;
			}
			dto.setRoomCode(modelKeyService.next(ModelEnum.PROJECT_ROOM));
			ProjectRoomDto mDto = service.create(dto);
			if (null == mDto) {
				response.fail("80000", "保存数据错误");
				return response;
			}
			response.success(mDto);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("保存数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(ProjectRoomDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			ProjectRoomDto mDto = new ProjectRoomDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<ProjectRoom> findById(Long id) {
		Response<ProjectRoom> response = new Response<ProjectRoom>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			ProjectRoom entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}
	@Override
	public ResponseList<ProjectRoom> findByDto(ProjectRoomDto dto) {
		ResponseList<ProjectRoom> response = new ResponseList<ProjectRoom>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<ProjectRoom> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<ProjectRoom> findPageByDto(ProjectRoomDto dto, Integer begin, Integer row) {
		Page<ProjectRoom> response = new Page<ProjectRoom>();
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}
			Page<ProjectRoom> page = service.getPageModel(dto, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Boolean> saveBatchData(String jsonArray) {
		Response<Boolean> response = new Response<Boolean>();
		if (StringUtils.isBlank(jsonArray)) {
			response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("批量修改房间信息"));
			return response;
		}
		try {
			JSONArray params = JSON.parseArray(jsonArray);
			int updateCount = 1;
			for (int i = 0; i < params.size(); i++) {
				JSONObject row = params.getJSONObject(i);
				ProjectRoomDto prd = JSONObject.toJavaObject(row, ProjectRoomDto.class);
				prd.setCombinedName(null);
				int count = service.update(prd);
				if (count > 0) {
					updateCount++;
				}
			}
			if (updateCount > 0) {
				response.success(Boolean.TRUE);
			} else {
				response.fail("90000", "量修改房间信息失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("批量修改房间信息错误：{}", e);
			;
		}
		return response;
	}

	@Override
	public Page<ProjectRoomPriceDto> findRoomPricePageByDto(ProjectRoomDto dto, Integer begin, Integer row) {
		Page<ProjectRoomPriceDto> resultPage = new Page<ProjectRoomPriceDto>();
		resultPage.setPageSize(row);
		try {
			if (StringUtils.isNotBlank(dto.getrStatus())) {
				String sql = new String(" AND room_status IN (1,3) ");
				dto.setrStatus(sql);
			}
			if (StringUtils.isNotBlank(dto.getcStatus())) {
				String sql = new String(" AND id IN (SELECT c.room_id FROM cus_tr_pay_deposit c WHERE c.is_paydeposit = 0) ");
				dto.setcStatus(sql);
			}
			if (null == dto || null == begin || null == row) {
				resultPage.setSuccess(false);
				resultPage.setErrorMsg("参数不合法");
				return resultPage;
			}
			/*if(StringUtils.isNotBlank(dto.getCustomerId())){
				//从客户跳转过来，则取客户所在项目
				Customer customer=customerService.selectById(Long.valueOf(dto.getCustomerId()));
				dto.setProjectId(customer.getProjectId());
			}else{*/
				//数据权限
				if(SysConstants.openDataPermission){
					String dataPermission = dataPermissionService.dataPermissionCondition(dto.getPermissionUserId(), dto.getResourcesCode(), dto.getPrefix(), dto.getColumnName());
					String [] dataPermissionArr = dataPermission.split(":");
					if("00".equals(dataPermissionArr[0])){
						resultPage.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
						resultPage.setSuccess(false);
						return resultPage;
					}
					dto.setDataPermission(dataPermissionArr[1]);
				}
			/*}*/
			
			
			List<ProjectRoomPriceDto> rows = new ArrayList<ProjectRoomPriceDto>();
			Page<ProjectRoom> page = service.getPageModel(dto, begin, row);
			if (null != page.getRows()) {
				for (ProjectRoom pt : page.getRows()) {
					ProjectRoomPriceDto prpd = new ProjectRoomPriceDto();
					// 复制属性
					BeanUtils.copyProperties(pt, prpd);
					prpd.setRoomStatusName(StringUtils.isNotBlank(prpd.getRoomStatus()) ? RoomStatusEnum.getByNo(
							prpd.getRoomStatus()).getDes() : "未知");
					// 查询价格
					PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(pt.getId());
					if (null != priceSchemeDetail) {
						prpd.setSetPrice(priceSchemeDetail.getSetPrice());
						prpd.setUnitPrice(priceSchemeDetail.getUnitPrice());
						prpd.setTotalPrice(priceSchemeDetail.getTotalPrice());
						prpd.setDiscountRate(priceSchemeDetail.getDiscountRate()==null?new BigDecimal("0"):priceSchemeDetail.getDiscountRate());
						prpd.setFloatingRange(priceSchemeDetail.getFloatingRange());
						//查询计价方式
						PriceScheme priceScheme=priceSchemeService.selectById(priceSchemeDetail.getPriceSchemeId());
						if (null != priceScheme) {
							String valuationType = priceScheme.getValuationType();
							prpd.setValuationType(valuationType);
							if (valuationType.equals("1")) {
								// 计价面积=建筑面积
								prpd.setBillingArea(pt.getBuildingArea());
								//折前单价=单价
								prpd.setCalculateUnitPrice(priceSchemeDetail.getUnitPrice());
							} else if (valuationType.equals("2")) {
								// 计价面积=套内面积
								prpd.setBillingArea(pt.getInnerArea());
								//折前单价=套内单价
								prpd.setCalculateUnitPrice(priceSchemeDetail.getUnitPrice());
							} else {
								// 计价面积=1
								prpd.setBillingArea(new BigDecimal(1));
								//折前单价=0
								prpd.setCalculateUnitPrice(BigDecimal.ZERO);
							}
						}
						if(null != priceScheme.getFloorType() && priceScheme.getFloorType().equals("0")){
							prpd.setDiscountAmount(priceSchemeDetail.getUnitPrice());
							prpd.setDiscountTotalAmount(priceSchemeDetail.getTotalPrice());
							//prpd.setDiscountRate(new BigDecimal("0.00"));
						}else if(null != priceScheme.getFloorType() && priceScheme.getFloorType().equals("1")){
							//设置折后单价=折前单价格*折扣
							double discountAmount=0;
							if(null!=prpd.getCalculateUnitPrice() && prpd.getDiscountRate().compareTo(new BigDecimal("0"))!=0){
								discountAmount=MathUtil.divide(prpd.getCalculateUnitPrice().multiply(prpd.getDiscountRate()), new BigDecimal("100"),2);	
							}else if(null!=prpd.getCalculateUnitPrice()&& prpd.getDiscountRate().compareTo(new BigDecimal("0"))==0){
								discountAmount=new Double(prpd.getCalculateUnitPrice().toString());
							}
							prpd.setDiscountAmount(new BigDecimal(discountAmount));
							//设置折后总价=折前总价*折扣
							double discountTotalAmount=0;
							if(null!=prpd.getTotalPrice() && prpd.getDiscountRate().compareTo(new BigDecimal("0"))!=0){
								discountTotalAmount=MathUtil.divide(prpd.getTotalPrice().multiply(prpd.getDiscountRate()), new BigDecimal("100"),2);	
							}else if(null!=prpd.getTotalPrice()&& prpd.getDiscountRate().compareTo(new BigDecimal("0"))==0){
								discountTotalAmount=new Double(prpd.getTotalPrice().toString());
							}
							prpd.setDiscountTotalAmount(new BigDecimal(discountTotalAmount));
						}
						prpd.setFloorType(priceScheme.getFloorType());
					}
					rows.add(prpd);
				}

			}
			resultPage = new Page<ProjectRoomPriceDto>(page.getTotal(), rows);
			resultPage.setPageSize(row);
			resultPage.setSuccess(true);
		} catch (Exception e) {
			resultPage.setSuccess(false);
			resultPage.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return resultPage;
	}
	
	public Response<ProjectRoomPriceDto> findProjectRoomPriceById(Long id) {
		Response<ProjectRoomPriceDto> response = new Response<ProjectRoomPriceDto>();
		try {
			ProjectRoom pt = service.selectById(id);
			ProjectRoomPriceDto prpd = new ProjectRoomPriceDto();
			// 复制属性
			BeanUtils.copyProperties(pt, prpd);
			prpd.setRoomStatusName(StringUtils.isNotBlank(prpd.getRoomStatus()) ? RoomStatusEnum.getByNo(prpd.getRoomStatus()).getDes() : "未知");
			// 查询价格
			PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(pt.getId());
			if (null != priceSchemeDetail) {
				prpd.setSetPrice(priceSchemeDetail.getSetPrice());
				prpd.setUnitPrice(priceSchemeDetail.getUnitPrice());
				prpd.setTotalPrice(priceSchemeDetail.getTotalPrice());
				prpd.setDiscountRate(priceSchemeDetail.getDiscountRate()==null?new BigDecimal("0"):priceSchemeDetail.getDiscountRate());
				prpd.setFloatingRange(priceSchemeDetail.getFloatingRange());
				//查询计价方式
				PriceScheme priceScheme=priceSchemeService.selectById(priceSchemeDetail.getPriceSchemeId());
				if (null != priceScheme) {
					String valuationType = priceScheme.getValuationType();
					prpd.setValuationType(valuationType);
					if (valuationType.equals("1")) {
						// 计价面积=建筑面积
						prpd.setBillingArea(pt.getBuildingArea());
						//折前单价=单价
						prpd.setCalculateUnitPrice(priceSchemeDetail.getUnitPrice());
					} else if (valuationType.equals("2")) {
						// 计价面积=套内面积
						prpd.setBillingArea(pt.getInnerArea());
						//折前单价=套内单价
						prpd.setCalculateUnitPrice(priceSchemeDetail.getUnitPrice());
					} else {
						// 计价面积=1
						prpd.setBillingArea(new BigDecimal(1));
						//折前单价=0
						prpd.setCalculateUnitPrice(BigDecimal.ZERO);
					}
				}
				if(null != priceScheme.getFloorType() && priceScheme.getFloorType().equals("0")){
					prpd.setDiscountAmount(priceSchemeDetail.getUnitPrice());
					prpd.setDiscountTotalAmount(priceSchemeDetail.getTotalPrice());
					//prpd.setDiscountRate(new BigDecimal("0.00"));
				}else if(null != priceScheme.getFloorType() && priceScheme.getFloorType().equals("1")){
					//设置折后单价=折前单价格*折扣
					double discountAmount=0;
					if(null!=prpd.getCalculateUnitPrice() && prpd.getDiscountRate().compareTo(new BigDecimal("0"))!=0){
						discountAmount=MathUtil.divide(prpd.getCalculateUnitPrice().multiply(prpd.getDiscountRate()), new BigDecimal("100"),2);	
					}else if(null!=prpd.getCalculateUnitPrice()&& prpd.getDiscountRate().compareTo(new BigDecimal("0"))==0){
						discountAmount=new Double(prpd.getCalculateUnitPrice().toString());
					}
					prpd.setDiscountAmount(new BigDecimal(discountAmount));
					//设置折后总价=折前总价*折扣
					double discountTotalAmount=0;
					if(null!=prpd.getTotalPrice() && prpd.getDiscountRate().compareTo(new BigDecimal("0"))!=0){
						discountTotalAmount=MathUtil.divide(prpd.getTotalPrice().multiply(prpd.getDiscountRate()), new BigDecimal("100"),2);	
					}else if(null!=prpd.getTotalPrice()&& prpd.getDiscountRate().compareTo(new BigDecimal("0"))==0){
						discountTotalAmount=new Double(prpd.getTotalPrice().toString());
					}
					prpd.setDiscountTotalAmount(new BigDecimal(discountTotalAmount));
				}
				prpd.setFloorType(priceScheme.getFloorType());
			}
			response.success(prpd);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.emm.yixun.estate.service.ProjectRoomServiceFacade#getRoomPricePageByDto(com.emm.yixun.common.model.dto.
	 * ProjectRoomDto, java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public Response<Page<ProjectRoomDto>> getProjectRoomDtoPage(ProjectRoomDto reqDto, Integer pageSize,Integer pageNumber) {
		Response<Page<ProjectRoomDto>> resDto = new Response<Page<ProjectRoomDto>>();
		try {
			
			//数据权限
			if(SysConstants.openDataPermission){
				String dataPermission = dataPermissionService.dataPermissionCondition(reqDto.getPermissionUserId(), reqDto.getResourcesCode(), reqDto.getPrefix(), reqDto.getColumnName());
				String [] dataPermissionArr = dataPermission.split(":");
				if("00".equals(dataPermissionArr[0])){
					resDto.setResultMessage(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					resDto.setSuccess(false);
					return resDto;
				}
				reqDto.setDataPermission(dataPermissionArr[1]);
			}
			Page<ProjectRoom> pageResult = service.getPageModel(reqDto, PageUtil.begin(pageNumber, pageSize), pageSize);
			List<ProjectRoomDto> listPRD=new ArrayList<ProjectRoomDto>(); 
			if(null!=pageResult && null!=pageResult.getRows()){
				for(ProjectRoom pr : pageResult.getRows()){
					ProjectRoomDto prd=new ProjectRoomDto();
					BeanUtils.copyProperties(pr, prd);
					RoomPriceSchemeDetailDto roomPriceSchemeDetailDto=priceSchemeDetailService.selectRoomSchemeByRoomId(pr.getId());
					if(null!=roomPriceSchemeDetailDto){
						prd.setEffectiveDate(roomPriceSchemeDetailDto.getMinEffectiveDate());
						prd.setDanjia(roomPriceSchemeDetailDto.getUnitPrice());
						prd.setZongjia(roomPriceSchemeDetailDto.getTotalPrice());
						prd.setValuationType(roomPriceSchemeDetailDto.getValuationType());
						String valuationType=roomPriceSchemeDetailDto.getValuationType();
						if (valuationType.equals("1")) {
							// 计价面积=建筑面积
							prd.setArea(String.valueOf(pr.getBuildingArea().doubleValue()));
							//折前单价=单价
						} else if (valuationType.equals("2")) {
							// 计价面积=套内面积
							prd.setArea(String.valueOf(pr.getInnerArea().doubleValue()));
						} else {
							//折前单价=0
							prd.setArea("0");
						}
					}
					String roomSecName = "";
					String prefix = "-->";
					roomSecName = nullToBlank(pr.getProjectSecName()) + prefix + nullToBlank(pr.getPremisesSecName()) + prefix
						+ nullToBlank(pr.getBuildingSecName()) + prefix + nullToBlank(pr.getUnitSecName())
						+ prefix + nullToBlank(pr.getRoomSecName());
					prd.setRoomSecName(roomSecName);
					ProjectHouseType projectHouseType=projectHouseTypeService.selectById(pr.getHouseTypeId());
					if(null!=projectHouseType)
						prd.setHouseTypeName(projectHouseType.getHouseTypeName());
					prd.setcStatus(RoomStatusEnum.getByNo(prd.getRoomStatus()).getDes());
					listPRD.add(prd);
					
				}
			}
			Page<ProjectRoomDto> page = new Page<ProjectRoomDto>(pageResult.getTotal(), listPRD);
			page.setPageSize(pageSize);
			resDto.setSuccess(true);
			resDto.setEntity(page);
			return resDto;
		} catch (Exception e) {
			logger.error("查询分页数据错误：{}", e);
			resDto.setSuccess(false);
			return resDto;
		}
	}

	public static String nullToBlank(String checkStr){
		if(StringUtils.isBlank(checkStr) || "null".equals(checkStr)){
			return "";
		}
		return checkStr;
	}

	@Override
	public Response<ProjectRoomPriceDto> findRoomPriceDetail(Long roomId) {
		Response<ProjectRoomPriceDto> result=new Response<ProjectRoomPriceDto>();
		try {
			ProjectRoom projectRoom=service.selectById(roomId);
			ProjectRoomPriceDto prpd = new ProjectRoomPriceDto();
			// 复制属性
			BeanUtils.copyProperties(projectRoom, prpd);
			prpd.setRoomStatusName(StringUtils.isNotBlank(prpd.getRoomStatus()) ? RoomStatusEnum.getByNo(
					prpd.getRoomStatus()).getDes() : "未知");
			// 查询价格
			PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(projectRoom.getId());
			if (null != priceSchemeDetail) {
				prpd.setSetPrice(priceSchemeDetail.getSetPrice());
				prpd.setUnitPrice(priceSchemeDetail.getUnitPrice());
				prpd.setTotalPrice(priceSchemeDetail.getTotalPrice());
				prpd.setDiscountRate(priceSchemeDetail.getDiscountRate()==null?new BigDecimal("0"):priceSchemeDetail.getDiscountRate());
				prpd.setFloatingRange(priceSchemeDetail.getFloatingRange());
				//查询计价方式
				PriceScheme priceScheme=priceSchemeService.selectById(priceSchemeDetail.getPriceSchemeId());
				if (null != priceScheme) {
					String valuationType = priceScheme.getValuationType();
					prpd.setValuationType(valuationType);
					if (valuationType.equals("1")) {
						// 计价面积=建筑面积
						prpd.setBillingArea(projectRoom.getBuildingArea());
						//折前单价=单价
						prpd.setCalculateUnitPrice(priceSchemeDetail.getUnitPrice());
					} else if (valuationType.equals("2")) {
						// 计价面积=套内面积
						prpd.setBillingArea(projectRoom.getInnerArea());
						//折前单价=套内单价
						prpd.setCalculateUnitPrice(priceSchemeDetail.getUnitPrice());
					} else {
						// 计价面积=1
						prpd.setBillingArea(new BigDecimal(1));
						//折前单价=0
						prpd.setCalculateUnitPrice(BigDecimal.ZERO);
					}
				}
				if(priceScheme.getFloorType().equals("0")){
					prpd.setDiscountAmount(priceSchemeDetail.getUnitPrice());
					prpd.setDiscountTotalAmount(priceSchemeDetail.getTotalPrice());
					//prpd.setDiscountRate(new BigDecimal("0.00"));
				}else if(priceScheme.getFloorType().equals("1")){
					//设置折后单价=折前单价格*折扣
					double discountAmount=0;
					if(null!=prpd.getCalculateUnitPrice() && prpd.getDiscountRate().compareTo(new BigDecimal("0"))!=0){
						discountAmount=MathUtil.divide(prpd.getCalculateUnitPrice().multiply(prpd.getDiscountRate()), new BigDecimal("100"),2);	
					}else if(null!=prpd.getCalculateUnitPrice()&& prpd.getDiscountRate().compareTo(new BigDecimal("0"))==0){
						discountAmount=new Double(prpd.getCalculateUnitPrice().toString());
					}
					prpd.setDiscountAmount(new BigDecimal(discountAmount));
					//设置折后总价=折前总价*折扣
					double discountTotalAmount=0;
					if(null!=prpd.getTotalPrice() && prpd.getDiscountRate().compareTo(new BigDecimal("0"))!=0){
						discountTotalAmount=MathUtil.divide(prpd.getTotalPrice().multiply(prpd.getDiscountRate()), new BigDecimal("100"),2);	
					}else if(null!=prpd.getTotalPrice()&& prpd.getDiscountRate().compareTo(new BigDecimal("0"))==0){
						discountTotalAmount=new Double(prpd.getTotalPrice().toString());
					}
					prpd.setDiscountTotalAmount(new BigDecimal(discountTotalAmount));
				}
				prpd.setFloorType(priceScheme.getFloorType());
				
			}
			result.success(prpd);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result.fail("80000", "查询错误");
		}
		return result;
	}

	@Override
	public Response<ProjectRoomPriceDto> findPayDeposit(Long roomId,Long payDeposit) {
		Response<ProjectRoomPriceDto>  projectPriceDto = new Response<ProjectRoomPriceDto>();
		try {
			ProjectRoom projectRoom=service.selectById(roomId);
			ProjectRoomPriceDto prpd = new ProjectRoomPriceDto();
			BeanUtils.copyProperties(projectRoom, prpd);
			prpd.setRoomStatusName(StringUtils.isNotBlank(prpd.getRoomStatus()) ? RoomStatusEnum.getByNo(
					prpd.getRoomStatus()).getDes() : "未知");
			projectPriceDto.setEntity(prpd);
			PayDeposit payDepositObj = payDepositService.selectById(payDeposit);
			//折前单价
			prpd.setCalculateUnitPrice(payDepositObj.getDiscountPrice());
			prpd.setTotalPrice(payDepositObj.getDiscountTotalPrice());
			prpd.setBillingArea(payDepositObj.getCalculateArea());
			prpd.setDiscountRate(payDepositObj.getDiscountRate());
			prpd.setFloatingRange(payDepositObj.getFloatingRange());
			if(payDepositObj.getFloorType().equals("0")){
				payDepositObj.setDiscountRate(new BigDecimal("0.00"));
			}
			//合同金额
			if(payDepositObj.getDiscountRate()!=null&&payDepositObj.getDiscountRate().compareTo(new BigDecimal("0.00"))!=0){
					prpd.setDiscountTotalAmount(payDepositObj.getDiscountTotalPrice().multiply(payDepositObj.getDiscountRate().divide(new BigDecimal(100))));
					prpd.setDiscountAmount(payDepositObj.getDiscountPrice().multiply(payDepositObj.getDiscountRate().divide(new BigDecimal(100))));
			}else{
				prpd.setDiscountTotalAmount(payDepositObj.getDiscountTotalPrice());
				prpd.setDiscountAmount(payDepositObj.getDiscountPrice());
			}
			prpd.setFloorType(payDepositObj.getFloorType());
			projectPriceDto.setSuccess(true);
		} catch (Exception e) {
			projectPriceDto.setSuccess(false);
			e.printStackTrace();
		}
		return projectPriceDto;
	}

	@Override
	public Response<ProjectRoomPriceDto> findSubscribe(Long roomId,Long subscribeId) {

		Response<ProjectRoomPriceDto>  projectPriceDto = new Response<ProjectRoomPriceDto>();
		try {
			ProjectRoom projectRoom=service.selectById(roomId);
			ProjectRoomPriceDto prpd = new ProjectRoomPriceDto();
			BeanUtils.copyProperties(projectRoom, prpd);
			prpd.setRoomStatusName(StringUtils.isNotBlank(prpd.getRoomStatus()) ? RoomStatusEnum.getByNo(
					prpd.getRoomStatus()).getDes() : "未知");
			projectPriceDto.setEntity(prpd);
			Subscribe subScribe = subscribeService.selectById(subscribeId);
			//折前单价
			prpd.setCalculateUnitPrice(subScribe.getConversionPrice());
			prpd.setTotalPrice(subScribe.getLumpsumPrice());
			prpd.setBillingArea(subScribe.getCalculateArea());
			prpd.setDiscountRate(subScribe.getDiscountRate());
			prpd.setFloatingRange(subScribe.getFloatingRange());
			//合同金额
			if(subScribe.getDiscountRate()!=null){
			prpd.setDiscountTotalAmount(subScribe.getSubscribeAmount());
			prpd.setDiscountAmount(subScribe.getSubscribePrice());
			}
			prpd.setDiscountAfterPrice(subScribe.getDiscountAfterPrice());
			prpd.setFloorType(subScribe.getFloorType());
			projectPriceDto.setSuccess(true);
		} catch (Exception e) {
			projectPriceDto.setSuccess(false);
			e.printStackTrace();
		}
		return projectPriceDto;
	}

	/**
	 * 根据项目ID查询项目房间业务数据
	 * 
	 * @param projectId
	 * @return ProjectRoom
	 */
	@Override
	public ProjectRoom selectProjectRoom(Long projectId) {
		return service.selectProjectRoom(projectId);
	}

	@Override
	public Response<Integer> updateByDto(ProjectRoomDto dto) {
		Response<Integer> response = new Response<Integer>();
		try {
			int count = service.update(dto);
			response.success(Integer.valueOf(count));
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	/**
	 * “回来了社区” 新增接口
	 * 
	 *（6）客户跟进信息增量更新接口(queryProjectRoomInfoList)
	 * @author liujunze
	 * 分页查询
	 */
	@Override
	public QueryProjectRoomInfoListResDto queryProjectRoomInfoPage(QueryProjectRoomInfoListReqDto reqDto) {
		QueryProjectRoomInfoListResDto resDto = new QueryProjectRoomInfoListResDto();
		List<ProjectRoomInfoListRes> projectRoomInfoList = new ArrayList<ProjectRoomInfoListRes>();
		//验证接口参数准确性
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		//验证分页参数时候正确
		Integer pageNum = reqDto.getPageNum();
		Integer pageSize = reqDto.getPageSize();
		if(null == pageNum || null == pageSize){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("pageNum或pageSize为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		//验证查询条件时候正确
		String starTime = reqDto.getStarTime(); //开始时间
		String endTime = reqDto.getEndTime(); //结束时间
		if(StringUtils.isBlank(starTime) 
				|| StringUtils.isBlank(endTime)){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("starTime或endTime为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		if(starTime.length() == 10){
			starTime = starTime + " 00:00:00";
		}
		if(endTime.length() == 10){
			endTime = endTime + " 23:59:59";
		}
		try {
			//验证授权码是否正确
			MerchantDto merDto = new MerchantDto();
			merDto.setMerchantCode(reqDto.getToken());
			merDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			Merchant merchant = merchantService.selectByDto(merDto);
			if (merchant == null) {
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("授权码验证失败！");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			
			//查询数据主体
			SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			ProjectRoomDto entity = new ProjectRoomDto();
			entity.setMerchantId(merchant.getId());
			entity.setUpdateTimeBefore(sft.parse(starTime));
			entity.setUpdateTimeAfter(sft.parse(endTime));
			Page<ProjectRoomDto> page = service
					.getProjectRoomInfoPage(entity, PageUtil.begin(pageNum, pageSize), pageSize);
			if(page.getRows() == null){
				resDto.setProjectRoomInfoList(new ArrayList<ProjectRoomInfoListRes>());
				resDto.setTotalPageNum(0L);
				resDto.setResult(ResultEnum.SUCCESS.getNo());
				return resDto;
			}
			
			//组装返回res
			ProjectRoomInfoListRes res = null;
			List<ProjectRoomDto> list = page.getRows();
			for(ProjectRoomDto dto : list){
				res = new ProjectRoomInfoListRes();
				res.setProjectCode(dto.getProjectCode()); //项目编号
				res.setProjectName(dto.getProjectName()); //项目名称
				res.setRoomId(dto.getId().toString());//房间Id
				res.setRoomCode(dto.getRoomCode()); //房间编号
				res.setCombinedName(dto.getCombinedName()); //管理对象
				res.setRoomName(dto.getRoomName()); //房间名称
				res.setFloor(dto.getFloor() == null ? "" : dto.getFloor().toString()); //楼层
				res.setProjectTypeName(StringUtils.isBlank(dto.getProjectType()) ? 
						"" : getValue(dto.getProjectType())); //房产类型
				res.setHouseTypeName(dto.getHouseTypeName()); //户型
				res.setCalculateArea(dto.getBillingArea() == null ? 
						"" : dto.getBillingArea().toString()); //计费面积
				res.setBuildingArea(dto.getBuildingArea() == null ? 
						"" : dto.getBuildingArea().toString()); //建筑面积
				res.setSharingArea(dto.getSharingArea() == null ? 
						"" : dto.getSharingArea().toString()); //分摊面积
				res.setGardenArea(dto.getGardenArea() == null ? 
						"" : dto.getGardenArea().toString()); //花园面积
				res.setFreeArea(dto.getFreeArea() == null ? 
						"" : dto.getFreeArea().toString()); //赠送面积
				res.setBasementArea(dto.getBasementArea() == null ? 
						"" : dto.getBasementArea().toString()); //地下室面积
				res.setUpdateDate(sft.format(dto.getUpdateTime())); //更新时间（通过sql判断，没有更新时间取创建时间）
				projectRoomInfoList.add(res);
			}
			resDto.setProjectRoomInfoList(projectRoomInfoList);
			resDto.setTotalPageNum((long)projectRoomInfoList.size());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			return resDto;
		} catch (Exception e) {
			logger.error("房产信息增量接口查询失败", e);
			resDto.setErrorCode("99999");
			resDto.setErrorMsg("房产信息查询失败");
			resDto.setResult(ResultEnum.FAILURE.getNo());
		}
		return resDto;
	}

	/**
	 * “回来了社区” 新增接口
	 * 
	 *（7）客户与房产关联关系表增量接口(queryCustomerRoomList)
	 * @author liujunze
	 * 分页查询
	 */
	@Override
	public QueryCustomerRoomListResDto queryCustomerRoomPage(QueryCustomerRoomListReqDto reqDto) {
		QueryCustomerRoomListResDto resDto = new QueryCustomerRoomListResDto();
		List<CustomerRoomListRes> customerRoomList = new ArrayList<CustomerRoomListRes>();
		
		//验证接口参数准确性
		boolean flag = DsfConfig.validSign(reqDto);
		if(!flag){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("接口参数验签失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		//验证分页参数时候正确
		Integer pageNum = reqDto.getPageNum();
		Integer pageSize = reqDto.getPageSize();
		if(null == pageNum || null == pageSize){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("pageNum或pageSize为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		//验证查询条件时候正确
		String starTime = reqDto.getStarTime(); //开始时间
		String endTime = reqDto.getEndTime(); //结束时间
		if(StringUtils.isBlank(starTime) 
				|| StringUtils.isBlank(endTime)){
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("starTime或endTime为空");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		if(starTime.length() == 10){
			starTime = starTime + " 00:00:00";
		}
		if(endTime.length() == 10){
			endTime = endTime + " 23:59:59";
		}
		
		try{
			//验证授权码是否正确
			MerchantDto merDto = new MerchantDto();
			merDto.setMerchantCode(reqDto.getToken());
			merDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			Merchant merchant = merchantService.selectByDto(merDto);
			if (merchant == null) {
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("授权码验证失败！");
				resDto.setResult(ResultEnum.FAILURE.getNo());
				return resDto;
			}
			
			//查询数据主体
			SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			SimpleDateFormat sft1 = new SimpleDateFormat("yyyy-MM-dd");
			ProjectRoomDto entity = new ProjectRoomDto();
			entity.setMerchantId(merchant.getId());
			entity.setUpdateTimeBefore(sft.parse(starTime));
			entity.setUpdateTimeAfter(sft.parse(endTime));
			Page<ProjectRoomDto> page = service
					.getCustomerRoomPage(entity, PageUtil.begin(pageNum, pageSize), pageSize);
			if(page.getRows() == null){
				resDto.setCustomerRoomList(new ArrayList<CustomerRoomListRes>());
				resDto.setTotalPageNum(0L);
				resDto.setResult(ResultEnum.SUCCESS.getNo());
				return resDto;
			}
			
			//组装返回res
			CustomerRoomListRes res = null;
			for(ProjectRoomDto dto : page.getRows()){
				res = new CustomerRoomListRes();
				
				res.setProjectName(dto.getProjectName()); //项目名称
				res.setProjectCode(dto.getProjectCode()); //项目编号
				res.setCustomerCode(dto.getCustomerCode()); //客户代码
				res.setCustomerName(dto.getCustomerName()); //客户名称
				res.setCombinedName(dto.getCombinedName()); //房号
				res.setSubscribeDate(dto.getSubscribeDate() == null ? 
						null : sft1.format(dto.getSubscribeDate())); //认购日期
				res.setCalculateArea(dto.getBillingArea() == null ? 
						null : dto.getBillingArea().toString()); //计费面积
				res.setRoomStatus(StringUtils.isBlank(dto.getRoomStatus()) ? 
						null : RoomStatusEnum.getByNo(dto.getRoomStatus()).getDes()); //房间状态
				res.setHouseTypeName(dto.getHouseTypeName()); //户型
				res.setSignedPrice(dto.getSignedPrice()); //签约单价
				res.setContractAmount(dto.getContractAmount()); //合同金额
				res.setConversionSignDate(dto.getConversionSignDate() == null ? 
						null : sft1.format(dto.getConversionSignDate())); //转签约时间
				res.setIsOverdue(dto.getIsOverdue()); //是否逾期未签约
				res.setOverdueDay(dto.getOverdueDay()); //逾期未签约天数
				res.setSubscribeAmount(dto.getSubscribeAmount()); //认购金
				res.setHaveSubscribeAmount(dto.getHaveSubscribeAmount()); //已收认购金
				res.setAgentCode(dto.getUserCode()); //经纪人代码
				res.setAgentName(dto.getUserName()); //经纪人
				res.setBusinessStatus(StringUtils.isBlank(dto.getBusinessStatus()) ? 
						null : BusinessStatusEnum.getByNo(dto.getBusinessStatus()).getDes()); //业务状态
				res.setBeforeDiscountPrice(dto.getBeforeDiscountPrice()); //折前单价
				res.setBeforeDiscountAmount(dto.getBeforeDiscountAmount()); //折前总价
				res.setSubscribeCode(dto.getSubscribeCode()); //认购编号
				res.setDiscountAmount(dto.getDiscountAmount()); //折扣金额
				res.setDiscountRate(dto.getDiscountRate()); //折扣比例
				res.setDiscountNote(dto.getDiscountNote()); //折扣说明
				res.setDealCategory(StringUtils.isBlank(dto.getDealCategory()) ? 
						null : DealCategoryEnum.getByNo(dto.getDealCategory()).getDes()); //成交类别
				res.setRoomDynamic(getRoomDynamic(dto.getId(), dto.getCombinedName())); //房源动态
				res.setAuditStatus(StringUtils.isBlank(dto.getAuditStatus()) ? 
						null : AuditStatusEnum.getByNo(dto.getAuditStatus()).getDes()); //审核状态
				res.setUpdateDate(sft.format(dto.getUpdateTime())); //更新时间（通过sql判断，没有更新时间取创建时间）
				
				customerRoomList.add(res);
			}
			resDto.setCustomerRoomList(customerRoomList);
			resDto.setTotalPageNum((long)customerRoomList.size());
			resDto.setResult(ResultEnum.SUCCESS.getNo());
			return resDto;
		}catch(Exception e){
			logger.error("客户与房产关联关系表增量接口", e);
			resDto.setErrorCode("99999");
			resDto.setErrorMsg("客户与房产关联关系查询失败");
			resDto.setResult(ResultEnum.FAILURE.getNo());
		}
		
		return resDto;
	}
	
	/**
	 * 多ID字段获取value
	 * @param str
	 * @return
	 */
	private String getValue(String str) {
		String[] ids = str.split(",");
		StringBuffer name = new StringBuffer();
		for (int ii = 0; ii < ids.length; ii++) {
			String id = ids[ii];
			if (ProjectTypeEnum.getByNo(id) != null) {
				name.append(ProjectTypeEnum.getByNo(id).getDes());
			}
			if (ii != (ids.length - 1)) {
				name.append(",");
			}
		}
		return name.toString();
	}
	
	/**
	 * 组装房源动态信息
	 * @return
	 */
	private String getRoomDynamic(Long roomId, String roomName){
		StringBuffer sb = new StringBuffer();
		
		SimpleDateFormat sft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		RoomChangeHistoryDto entity = new RoomChangeHistoryDto();
		entity.setRoomId(roomId);
		entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
		entity.addAsc("create_time");
		List<RoomChangeHistory> list = roomChangeHistoryService.selectListByDto(entity);
		if(list == null){
			return sb.toString();
		}
		sb.append("[");
		for(int i = 0; i < list.size(); i++){
			RoomChangeHistory rh = (RoomChangeHistory)list.get(i);
			
			sb.append("[\"");
			sb.append(rh.getBusinessDynamics()); //房间状态
			sb.append("\",\"");
			sb.append(roomName); //房源
			sb.append("\",\"");
			sb.append(rh.getRemark()); //备注
			sb.append("\",\"");
			sb.append(sft.format(rh.getCreateTime())); //操作日期
			sb.append("\",\"");
			sb.append(rh.getCreateManageCN()); //操作人
			sb.append("\",\"");
			sb.append(rh.getUserCode()); //操作人code
			if((list.size() - 1) == i){
				sb.append("\"]");
			}else{
				sb.append("\"],");
			}
		}
		sb.append("]");
		return sb.toString();
	}
	
	@Override
	public ResponseList<ProjectRoom> findRepairDataRoomByDto(ProjectRoomDto dto) {
		ResponseList<ProjectRoom> response = new ResponseList<ProjectRoom>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<ProjectRoom> list = service.selectRepairDataRoomListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public GraphicalVo<PicHighchartsVo> findIndustData(Long projectId) {
		GraphicalVo<PicHighchartsVo> vo = new GraphicalVo<PicHighchartsVo>();
		try {
			List<PicHighchartsVo> data = service.findIndustData(projectId);
			vo.setName("业态房间占比");
			vo.setData(data);
		} catch (Exception e) {
			logger.error("error",e);
		}
		return vo;
	}
}
